#include "qmidimark.h"
#include "qmidihelper.h"
#include "allegro.h"
#include <QFileInfo>
#include <QHeaderView>

using namespace midiHelper;

QMidiMark::QMidiMark(QWidget *parent)
	: QTableWidget(parent)
{
	auto size = QSize(400, 300);
	resize(size);

	setColumnCount(3);

	QStringList header;
	header << "HMSF" << "MBT" << "Name";
	setHorizontalHeaderLabels(header);

	horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
	//verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
	setEditTriggers(QAbstractItemView::NoEditTriggers);
}

QMidiMark::~QMidiMark()
{
}

void QMidiMark::open(const QString& path)
{
	if (path.isEmpty())
	{
		Q_ASSERT(false);
		return;
	}

	QFileInfo fileInfo(path);
	if (!fileInfo.isFile())
	{
		Q_ASSERT(false);
		return;
	}

	Alg_seq seq(path.toStdString().c_str(), true);
	Alg_seq_ptr new_seq = &seq;
	if (new_seq->get_read_error() != alg_no_error)
	{
		Q_ASSERT(false);
		return;
	}

	clearContents();
	setRowCount(0);

	struct mark_Item
	{
		Alg_event_ptr event;
		double timeSeconds;
		double timeTicks;
	};

	// make sure time is seconds
	new_seq->convert_to_seconds();

	QList<mark_Item> items;
	auto& marks = getMarkEvents(new_seq);
	if (marks.size() < 1)
	{
		return;
	}

	for (auto& mark : marks)
	{
		mark_Item item;
		item.event = mark;
		item.timeSeconds = mark->time;
		item.timeTicks = 0;
		items.push_back(item);
	}

	// make sure time is beats
	new_seq->convert_to_beats();

	setRowCount(items.size());

	int iRow = 0;
	for (auto& item : items)
	{
		item.timeTicks = item.event->time * new_seq->division;

		// HMSF
		QString HMSF = secondsToHMSF(item.timeSeconds);
		setItem(iRow, 0, new QTableWidgetItem(HMSF));
		this->item(iRow, 0)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);

		// MBT
		QString MBT = ticksToMBT(new_seq, item.timeTicks);
		setItem(iRow, 1, new QTableWidgetItem(MBT));
		this->item(iRow, 1)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);

		// name
		QString name(QString::fromLocal8Bit(item.event->get_string_value()));
		setItem(iRow, 2, new QTableWidgetItem(name));
		this->item(iRow, 2)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);

		++iRow;
	}
}
